<?php
/**
 * Created by PhpStorm.
 * User: wjj
 * Date: 2016/11/1
 */

namespace app\logic;



use app\models\Category;
use yii;


class CategoryLogic
{

    public function addCategory($parent_id=0,$level=1,$category_name,$category_sort=0){
        $category = new Category();
        $category->parent_id = $parent_id;
        $category->level = $level;
        $category->category_name = $category_name;
        $category->category_sort = $category_sort;
        $category->save();
        return $category->category_id;
    }

    public function getCategory($query = [], $page = 1, $limit = 10)
    {
        $category = Category::find()->filterWhere($query)->orderBy('category_sort asc, category_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $category->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $category->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'category/index',
                'query' => $query
            ]
        ];
        return $return;
    }

    public function getCategoryByYx($yx_category_id){
        return Category::findOne(['yx_category_id' => $yx_category_id]);
    }

    public function getSubCategory($id)
    {
        return Category::find()->where(["parent_id"=>$id,"level"=>2])->orderBy('category_sort asc, category_id desc')->asArray()->all();
    }

    public function getById($id)
    {
        return Category::find()->where(['category_id' => $id])->asArray()->one();
    }

    public function editCategoryById($id, $params, $uploadresult)
    {
        if(!$category = Category::findOne($id)) return false;
        $category->category_sort = $params['category_sort'];
        if($uploadresult)
            $category->category_pic = $uploadresult;
        return $category->save();
    }





}
